package com.myself.source.module.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.myself.common.define.model.CurrentUser;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RequiredArgsConstructor
public class HeadThreadlocalFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String userInfoStr = request.getHeader("UserInfo");
        if (StrUtil.isBlank(userInfoStr)){
              filterChain.doFilter(request, servletResponse);
              return;
        }
        CurrentUser currentUser = JSONUtil.toBean(userInfoStr, CurrentUser.class);
        UserUtils.setLoginUser(currentUser);
        filterChain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {
        UserUtils.removeUser();
    }
}
